var textArry5 = {
    id: "1",
    name: "文字控件",
    height: "140",
    data: [
        {
            key: "onwText",
            category: "文字一",
            classifty: "textShape",
            type: 3,
            color: "#1E9FFF",
            textColor: "#fff",
            text: "文字"
        },
        {
            key: "twoText",
            category: "文字二",
            classifty: "textShape",
            type: 3,
            color: "#569bd5",
            textColor: "#fff",
            text: "文字"
        },
        {
            key: "threeText",
            category: "文字三",
            classifty: "textShape",
            type: 3,
            color: "#a9a9e9",
            textColor: "#fff",
            text: "文字"
        }
    ]
};
var classifylist = [];

function init() {
    menusList();
    objGo = go.GraphObject.make; // 创建画布
    myDiagram = objGo(go.Diagram, "myDiagramDiv", // 必须命名或引用div html元素
        {
            "grid": objGo(go.Panel, "Grid",
                objGo(go.Shape, "LineH", {stroke: "lightgray", strokeWidth: 0.5}),
                objGo(go.Shape, "LineH", {stroke: "gray", strokeWidth: 0.5, interval: 10}),
                objGo(go.Shape, "LineV", {stroke: "lightgray", strokeWidth: 0.5}),
                objGo(go.Shape, "LineV", {stroke: "gray", strokeWidth: 0.5, interval: 10})
            ),
            "grid.gridCellSize": new go.Size(10, 8),
            "allowDrop": true,  // 允许拖拽
            "initialContentAlignment": go.Spot.Center, // 居中显示
            "draggingTool.dragsLink": true,
            "draggingTool.isGridSnapEnabled": true,
            "linkingTool.isUnconnectedLinkValid": true,
            "linkingTool.portGravity": 20,
            "relinkingTool.isUnconnectedLinkValid": true,
            "relinkingTool.portGravity": 20,
            "relinkingTool.fromHandleArchetype":
                objGo(go.Shape, "Diamond", {
                    segmentIndex: 0,
                    cursor: "pointer",
                    desiredSize: new go.Size(8, 8),
                    fill: "tomato",
                    stroke: "darkred"
                }),
            "relinkingTool.toHandleArchetype":
                objGo(go.Shape, "Diamond", {
                    segmentIndex: -1,
                    cursor: "pointer",
                    desiredSize: new go.Size(8, 8),
                    fill: "darkred",
                    stroke: "tomato"
                }),
            "linkReshapingTool.handleArchetype":
                objGo(go.Shape, "Diamond", {desiredSize: new go.Size(7, 7), fill: "lightblue", stroke: "deepskyblue"}),
            rotatingTool: objGo(TopRotatingTool),  // defined below
            "rotatingTool.snapAngleMultiple": 15,
            "rotatingTool.snapAngleEpsilon": 15,
            "ChangedSelection": onSelectionChanged,
            "undoManager.isEnabled": true,
            // "ModelChanged": function(e) {     // 模块改变，生成相应的json文件
            //   if (e.isTransactionFinished) {  // json格式文件
            //      console.log(e.model.toJson())
            //   }
            // }
        });

    myDiagram.linkTemplate =
        objGo(go.Link,
            {
                routing: go.Link.AvoidsNodes,
                curve: go.Link.JumpOver,
                corner: 10,
                relinkableFrom: true,
                relinkableTo: true,
                reshapable: true,
                resegmentable: true,
                toShortLength: 7
            },
            new go.Binding("points").makeTwoWay(),
            objGo(go.Shape, {isPanelMain: true, stroke: "#1E9FFF", strokeWidth: 6}),// 线的边
            objGo(go.Shape, {isPanelMain: true, stroke: "#3a77e2", strokeWidth: 4}), // 线的背景颜色
            objGo(go.Shape, {
                isPanelMain: true,
                stroke: "#f5f5f5",
                strokeWidth: 2,
                name: "PIPE",
                strokeDashArray: [10, 10]
            }), // 中间流动的
            objGo(go.Shape, {toArrow: "Triangle", fill: "#3a77e2", stroke: null}), // 箭头的颜色
        );

    sharedToolTip =
        objGo(go.Adornment, "Auto",
            objGo(go.Shape, "RoundedRectangle", {fill: "lightyellow"}),
            objGo(go.TextBlock, {margin: 2},
                new go.Binding("text", "", function (d) {
                    return d.category;
                })));

    nodeResizeAdornmentTemplate =
        objGo(go.Adornment, "Spot",
            {locationSpot: go.Spot.Right},
            objGo(go.Placeholder),
            objGo(go.Shape, {
                alignment: go.Spot.TopLeft,
                cursor: "nw-resize",
                desiredSize: new go.Size(4, 4),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                alignment: go.Spot.Top,
                cursor: "n-resize",
                desiredSize: new go.Size(2, 2),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                alignment: go.Spot.TopRight,
                cursor: "ne-resize",
                desiredSize: new go.Size(4, 4),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),

            objGo(go.Shape, {
                alignment: go.Spot.Left,
                cursor: "w-resize",
                desiredSize: new go.Size(2, 2),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                alignment: go.Spot.Right,
                cursor: "e-resize",
                desiredSize: new go.Size(2, 2),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),

            objGo(go.Shape, {
                alignment: go.Spot.BottomLeft,
                cursor: "se-resize",
                desiredSize: new go.Size(4, 4),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                alignment: go.Spot.Bottom,
                cursor: "s-resize",
                desiredSize: new go.Size(2, 2),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                alignment: go.Spot.BottomRight,
                cursor: "sw-resize",
                desiredSize: new go.Size(4, 4),
                fill: "lightblue",
                stroke: "deepskyblue"
            })
        );

    nodeRotateAdornmentTemplate =
        objGo(go.Adornment,
            {locationSpot: go.Spot.Center, locationObjectName: "CIRCLE"},
            objGo(go.Shape, "Circle", {
                name: "CIRCLE",
                cursor: "pointer",
                desiredSize: new go.Size(8, 8),
                fill: "lightblue",
                stroke: "deepskyblue"
            }),
            objGo(go.Shape, {
                geometryString: "M4.2 8 L4.2 30",
                isGeometryPositioned: true,
                stroke: "deepskyblue",
                strokeWidth: 1.0,
                strokeDashArray: [4, 2]
            })
        );

    // 根据数据定义菜单分类
    paletteArry = []

    for (var item of classifylist) {
        let contentDataImg = {};
        contentDataImg.paletteDefine = new go.Palette("classify-" + item.id);
        contentDataImg.id = item.id;
        contentDataImg.data = item.data;
        for (var itemm of item.data) { // 每个分类里的图片
            var node;
            if (itemm.classifty === "img") {
                node = objGo(go.Node, "Spot", nodeStyle(),
                    objGo(go.Panel, "Auto",
                        {name: "PANEL"},
                        new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(go.Size.stringify),
                        objGo(go.Shape, "Rectangle",  // default figure
                            {
                                portId: "",
                                fromLinkable: true, margin: 0, toLinkable: true, cursor: "pointer",
                                fill: "rgba(70,113,196,0)",  // default color
                                strokeWidth: 0
                            },
                        ),
                        objGo(go.Picture,
                            {width: itemm.width - 5, height: itemm.height - 5},
                            new go.Binding("source"),
                            new go.Binding("width"),
                            new go.Binding("height"),
                        ),
                    ),
                    makePort("top", go.Spot.Top, true, true),
                    makePort("left", go.Spot.Left, true, true),
                    makePort("right", go.Spot.Right, true, true),
                    makePort("botton", go.Spot.Bottom, true, true),
                    {
                        mouseEnter: function (e, node) {
                            showSmallPorts(node, true);
                        },
                        mouseLeave: function (e, node) {
                            showSmallPorts(node, false);
                        }
                    }
                );
            } else if (itemm.classifty === "shape") {
                node = objGo(go.Node, "Spot", nodeStyle(),
                    objGo(go.Shape, "Rectangle",
                        {strokeWidth: 1, fill: "#8fbdee"},
                        new go.Binding("figure")),
                    makePort("top", go.Spot.Top, true, true),
                    makePort("left", go.Spot.Left, true, true),
                    makePort("right", go.Spot.Right, true, true),
                    makePort("botton", go.Spot.Bottom, true, true),
                    {
                        mouseEnter: function (e, node) {
                            showSmallPorts(node, true);
                        },
                        mouseLeave: function (e, node) {
                            showSmallPorts(node, false);
                        }
                    }
                );
            } else if (itemm.classifty === "textBlock") {
                node = objGo(go.Node, "Spot", nodeStyle(),
                    objGo(go.TextBlock,
                        {
                            font: "normal 11pt Helvetica, Arial, sans-serif",
                            margin: 8,
                            maxSize: new go.Size(160, NaN),
                            editable: true, stroke: "#0A7EF7",
                        },
                        new go.Binding("text").makeTwoWay(),
                        new go.Binding("stroke", "color"),
                    )
                );
            } else if (itemm.classifty === "textShape" && itemm.type === 4) {
                node = objGo(go.Node, "Horizontal", nodeStyleNo(),
                    {background: "#c1c4ee"},
                    objGo(go.TextBlock,
                        // 文字周围的空隙, 大号字体, 白色笔画:
                        {
                            font: "normal 11pt Helvetica, Arial, sans-serif",
                            margin: 6,
                            maxSize: new go.Size(160, 25),
                            wrap: go.TextBlock.WrapFit,
                            editable: true,
                            stroke: itemm.textColor,
                        },
                        new go.Binding("text").makeTwoWay()),
                    objGo(go.Panel, "Auto",
                        objGo(go.Shape, "Rectangle",
                            {
                                portId: "",
                                fromLinkable: true, margin: 0, toLinkable: true, cursor: "pointer",
                                fill: "#1E9FFF",  // default color
                                width: 60,
                                height: 30,
                                strokeWidth: 0,
                            },
                        ),
                        objGo(go.TextBlock,
                            {
                                font: "normal 11pt Helvetica, Arial, sans-serif",
                                margin: 8,
                                editable: true,
                                text: "生效",
                                stroke: "#fff"
                            },
                        ),
                    ),
                    new go.Binding("strokeWidth"),
                    makePort("top", go.Spot.Top, true, true),
                    makePort("left", go.Spot.Left, true, true),
                    makePort("right", go.Spot.Right, true, true),
                    makePort("botton", go.Spot.Bottom, true, true),
                    {
                        mouseEnter: function (e, node) {
                            showSmallPorts(node, true);
                        },
                        mouseLeave: function (e, node) {
                            showSmallPorts(node, false);
                        }
                    }
                );
            } else if (itemm.classifty === "textShape") {
                node = objGo(go.Node, "Spot", nodeStyle(),
                    objGo(go.Panel, "Auto",
                        {name: "PANEL"},
                        new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(go.Size.stringify),
                        objGo(go.Shape, "Rectangle",
                            {
                                portId: "",
                                fromLinkable: true, margin: 0, toLinkable: true, cursor: "pointer",
                                fill: itemm.color,  // default color
                                strokeWidth: 0,
                            },
                            new go.Binding("strokeWidth"),
                        ),
                        objGo(go.TextBlock,
                            {
                                font: "normal 11pt Helvetica, Arial, sans-serif",
                                margin: 8,
                                maxSize: new go.Size(160, NaN),
                                wrap: go.TextBlock.WrapFit,
                                editable: true,
                                stroke: itemm.textColor,
                            },
                            new go.Binding("stroke"),
                            new go.Binding("text").makeTwoWay())
                    ),
                    makePort("top", go.Spot.Top, true, true),
                    makePort("left", go.Spot.Left, true, true),
                    makePort("right", go.Spot.Right, true, true),
                    makePort("botton", go.Spot.Bottom, true, true),
                    {
                        mouseEnter: function (e, node) {
                            showSmallPorts(node, true);
                        },
                        mouseLeave: function (e, node) {
                            showSmallPorts(node, false);
                        }
                    }
                );
            }
            myDiagram.nodeTemplateMap.add(itemm.category, node);
        }
        paletteArry.push(contentDataImg);
    }
    for (var itemList of paletteArry) {
        itemList.paletteDefine.nodeTemplateMap = myDiagram.nodeTemplateMap;
        var nodeDataList = [];
        for (var itemChart of itemList.data) {
            if (itemChart.key.indexOf('开关') >= 0) {
                nodeDataList.push({
                    key: itemChart.key,
                    category: itemChart.category,
                    "source": itemChart.src,
                    'text': ''
                })
            } else if (itemChart.classifty == "img") {
                nodeDataList.push({key: itemChart.key, category: itemChart.category, "source": itemChart.src})
            } else if (itemChart.classifty == "shape") {
                nodeDataList.push({key: itemChart.key, category: itemChart.category, figure: itemChart.figure})
            } else if (itemChart.classifty == "textBlock") {
                nodeDataList.push({key: itemChart.key, category: itemChart.category})
            } else if (itemChart.classifty == "textShape") {
                nodeDataList.push({key: itemChart.key, category: itemChart.category, text: itemChart.text})
            }
        }
        itemList.paletteDefine.model.nodeDataArray = nodeDataList
    }
    setTimeout(function () {
        for (var itemList of paletteArry) {
            $("#classify-" + itemList.id).css('display', "none")
        }
    }, 100)

}

//菜单
function menusList() {
    var menusHtml = ''
    for (var item of classifylist) {

        menusHtml = ' <div class="classify-title" onclick="classifyShow(' + item.id + ')">' + item.name + '</div>'
            + '<div id="classify-' + item.id + '" class="classify-title-content" style="height: ' + item.height + 'px" ></div>'
        $("#myPaletteDiv").append(menusHtml);

    }
}

// 菜单显示内容
function classifyShow(showId) {
    if ($("#classify-" + showId).css('display') == "block") {
        $("#classify-" + showId).css('display', "none");
        $(".classify-" + showId).css('display', "none");
    } else {
        $(".classify-title-content").css('display', "none")
        $("#classify-" + showId).css('display', "block");
        $(".classify-" + showId).css('display', "block");
    }
}

// 组件样式定义
function nodeStyle() {
    return [new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        {resizable: true, resizeObjectName: "PANEL", resizeAdornmentTemplate: nodeResizeAdornmentTemplate},
        {rotatable: true, rotateAdornmentTemplate: nodeRotateAdornmentTemplate},
        new go.Binding("angle").makeTwoWay(),
        new go.Binding("isShadowed", "isSelected").ofObject(),
        {
            selectionAdorned: false,
            shadowOffset: new go.Point(0, 0),
            shadowBlur: 15,
            shadowColor: "#00a9c9",
            toolTip: sharedToolTip
        }];
}

function nodeStyleNo() {
    return [new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        {rotatable: true, rotateAdornmentTemplate: nodeRotateAdornmentTemplate},
        new go.Binding("angle").makeTwoWay(),
        new go.Binding("isShadowed", "isSelected").ofObject(),
        {
            selectionAdorned: false,
            shadowOffset: new go.Point(0, 0),
            shadowBlur: 15,
            shadowColor: "#00a9c9",
            toolTip: sharedToolTip
        }];
}

function showSmallPorts(node, show) {
    node.ports.each(function (port) {
        if (port.portId !== "") {  // don't change the default port, which is the big shape
            port.fill = show ? "rgba(58,160,255,1)" : null;
        }
    });
}

// 默认连线的链接位置
function makePort(name, spot, output, input) {
    let makePortWidth = 10;
    var shapeStr = "";
    switch (name) {
        case "top":
            shapeStr = "TriangleUp";
            break;
        case "right":
            shapeStr = "TriangleRight";
            break;
        case "botton":
            shapeStr = "TriangleDown";
            break;
        case "left":
            shapeStr = "TriangleLeft";
            break;
    }

    return objGo(go.Shape, shapeStr,
        {
            fill: null,  // not seen, by default; set to a translucent gray by showSmallPorts, defined below
            stroke: null,
            strokeWidth: 0,
            desiredSize: new go.Size(makePortWidth, makePortWidth),
            alignment: spot,  // align the port on the main Shape
            alignmentFocus: spot,  // just inside the Shape
            portId: name,  // declare this object to be a "port"
            fromSpot: spot,  // declare where links may connect at this port
            fromLinkable: output,  // declare whether the user may draw links from here
            toSpot: spot,  // declare where links may connect at this port
            toLinkable: input,  // declare whether the user may draw links to here
            cursor: "pointer"  // show a different cursor to indicate potential link point
        });
}

function onSelectionChanged(e) {
    $('#select_value').val('');
    $('#conponentName').val('');
    var node = e.diagram.selection.first();
    if (node instanceof go.Node) {
        updateProperties(node.data);
    } else {
        updateProperties(null);
    }
}

//RotatingTool用于通过设置GraphObject.angle属性以交互方式更改GraphObject的GraphObject.angle。
function TopRotatingTool() {
    go.RotatingTool.call(this);
}

go.Diagram.inherit(TopRotatingTool, go.RotatingTool);

TopRotatingTool.prototype.updateAdornments = function (part) {
    go.RotatingTool.prototype.updateAdornments.call(this, part);
    var adornment = part.findAdornment("Rotating");
    if (adornment !== null) {
        if (adornment.$d.size && adornment.$d.key.indexOf('Shape') < 0) {
            ratateImg = setTimeout(function () {
                let nodeData = myDiagram.model.findNodeDataForKey(adornment.$d.key);
                nodeData.width = parseInt(adornment.$d.size.split(' ')[0]) - 5;
                nodeData.height = parseInt(adornment.$d.size.split(' ')[1]) - 5;
                myDiagram.model.updateTargetBindings(nodeData);
                clearTimeout(ratateImg)
            }, 200)
        }
        adornment.location = part.rotateObject.getDocumentPoint(new go.Spot(0.5, 0, 0, -30));  // above middle top
    }
};

TopRotatingTool.prototype.rotate = function (newangle) {
    go.RotatingTool.prototype.rotate.call(this, newangle + 90);
};

function ConponentListInit(res) {
    let ii = 2;
    classifylist.splice(0, classifylist.length);
    classifylist.push(textArry5);
    res.rows.forEach(function (e) {
        let i = 0;
        classifylist.forEach(function (j, index, arr) {
            if (e.type === j.name) {
                i++;
                let d = {
                    src: e.data,
                    classifty: 'img',
                    category: e.label,
                    type: 2,
                    key: e.id.toString(),
                    width: 80,
                    height: 80
                }
                classifylist[index].data.push(d);
            }
        })
        if (i === 0) {
            let classifyeme = {
                id: (ii++).toString(),
                name: e.type,
                height: "300",
                data: [{
                    src: e.data,
                    classifty: 'img',
                    category: e.label,
                    type: 2,
                    key: e.id.toString(),
                    width: 80,
                    height: 80
                }]
            }
            classifylist.push(classifyeme);
        }
    })
}

//先选择所在位置，初始化车间名称
$.ajax({
    type: 'get',
    url: '/chart/queryLocationByBusinessId',
    data: {
        'businessId': label_id
    },
    dataType: 'json',
    async: false,
    contentType: "application/json; charset=utf-8",
    success: function (res) {
        let data = res.data
        $('#work_id').empty();
        for (var i = 0; i < data.length; i++) {
            $("#work_id").append(
                "<option value='" + data[i] + "'>" + data[i] +
                "</option>");
        }
    },
});

//获取控件栏
$.ajax({
    type: 'get',
    url: '/component/select',
    data: {
        'cname': companyName
    },
    dataType: 'json',
    async: false,
    contentType: "application/json; charset=utf-8",
    success: function (res) {
        ConponentListInit(res);
    },
});

init();// 初始化组件内容


function workIdChange() {
    getSelectNo();
    $('#select_type').val("");
    $('#select_value').val();
}

function selectNoChange() {
    getSelectType();
    $('#select_value').val();
}


//设备编号点击关联模块
function selectTypeChange() {
    getValue()
    getName()
    change($("#work_id").val(), $("#select_no").val(), $('#select_type').val());
}


function getSelectNo() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorTypeByLocation',
        data: {
            'businessId': label_id,
            'location': $("#work_id").val()
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {

            let data = res.data

            $('#select_no').empty();
            for (var i = 0; i < data.length; i++) {
                $("#select_no").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
        },
    });
}

/**
 * 获取设备编号
 */
function getSelectType() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorIdByLocationAndType',
        data: {
            'businessId': label_id,
            'location': $("#work_id").val(),
            'sensorType': $("#select_no").val(),
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {

            let data = res.data
            $('#select_type').empty();
            for (var i = 0; i < data.length; i++) {
                $("#select_type").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
            // $("#select_type").trigger("change")
        },
    });
}


/**
 * 获取选择设备编号对应设备的最新值
 */
function getValue() {
    if ($('#select_type').val() && $('#select_type').val().length !== 0) {
        $.ajax({
            type: 'get',
            url: '/entity_water/query_new_value_by_sensor_row_id',
            data: {
                'businessId': label_id,
                'sensorRowId': $("#select_type").val(),
            },
            dataType: 'json',
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (res) {

                let data = res.data
                $('#select_value').val(data)
            },
        });
    }
}

/**
 * 获取选择设备编号对应设备的名称
 */
function getName() {
    if ($('#select_type').val() && $('#select_type').val().length !== 0) {
        $.ajax({
            type: 'get',
            url: '/chart/selectOneName',
            data: {
                'businessId': label_id,
                'sensorRowId': $("#select_type").val(),
            },
            dataType: 'json',
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                $('#conponentName').val(res.name)
            },
            error: function () {
                bootoast({
                    message: '失败',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    }
}

//function getDeviceValue(businessId, deviceId) {
//    device_data = null;
//    $.ajax({
//        type: 'get',
//        url: '/entity_water/query_value_by_sensor_row_id',
//        data: {
//            'businessId': businessId,
//            'sensorRowId': deviceId,
//        },
//        dataType: 'json',
//        async: false,
//        contentType: "application/json; charset=utf-8",
//        success: function (res) {
//           device_data = res.data
//        },
//    });
//    return device_data;
//}

var bigdata;

function properties(work_id, select_no, name) {
    $("#form").empty();
    for (var i = 0; i < bigdata.results.length; i++) {
        if (bigdata.results[i].名称 === name) {
            for (var p in bigdata.results[i]) {
                if (p != "名称" && p != "设备类名" && p != "OPERATOR") {
                    var Odiv = document.createElement("div"); //创建一个div
                    var Ospan = document.createElement("span"); //创建一个span
                    var Oinput = document.createElement("input");

                    Odiv.setAttribute('class', 'input-group');
                    Odiv.style.margin = "10px 10px 10px";
                    Ospan.setAttribute('class', 'input-group-addon');
                    Ospan.style.width = "90px";
                    Ospan.appendChild(document.createTextNode(p));

                    Oinput.setAttribute('type', 'text');
                    Oinput.setAttribute('id', p);
                    Oinput.setAttribute('class', 'form-control');
                    Oinput.setAttribute('value', bigdata.results[i][p]);
                    Oinput.setAttribute('readonly', 'readonly');
                    Odiv.appendChild(Ospan); //在div内创建一个span
                    Odiv.appendChild(Oinput);
                    $("#form").append(Odiv);
                }
            }
        }
    }

}

function updateProperties(data) {
    if (data === null) {
        document.getElementById("propertiesPanel").style.display = "none";
    } else {
        document.getElementById("propertiesPanel").style.display = "block";
        $('#work_id').val(data['work_id']);
        getSelectNo();
        $('#select_no').val(data['select_type']);
        getSelectType();
        $('#select_type').val(data['select_no']);
        getValue();
        getName();
        $("#form").empty();
        if (data.name != null) {
            properties(data.work_id, data.select_type, data.select_no);
        }
    }
}

function change(work_id, select_type, name) {

    var node = myDiagram.selection.first();
    var data = node.data;
    if (node instanceof go.Node && data !== null) {
        var model = myDiagram.model;
        model.startTransaction("modified " + "work_id");
        model.startTransaction("modified " + "select_type");
        model.startTransaction("modified " + "select_no");
        model.setDataProperty(data, "work_id", work_id);
        model.setDataProperty(data, "select_type", select_type);
        model.setDataProperty(data, "select_no", name);
        model.commitTransaction("modified " + "work_id");
        model.commitTransaction("modified " + "select_type");
        model.commitTransaction("modified " + "select_no");
    }
    properties(work_id, select_type, name);

}


//  以JSON格式显示用户可编辑的图表模型
function save() {
    saveDiagramProperties(); // do this first, before writing to JSON
    document.getElementById("mySavedModel").value = myDiagram.model
        .toJson();
    myDiagram.isModified = false;
    var name = $('#flowchart_name').val();
    if (name === "") {
        bootoast({
            message: '请输入流程图名称',
            position: 'top',
            type: 'warning',
            timeout: 1.5,
        });
    } else {
        var values = {
            "chartName": name,
            "data": myDiagram.model.toJson(),
            "businessId": label_id
        };
        $.ajax({
            type: 'POST',
            data: JSON.stringify(values),
            contentType: 'application/json',
            dataType: 'json',
            url: "/chart/insert",
            success: function (data) {
                if (data.status === "success") {
                    bootoast({
                        message: '保存成功',
                        position: 'top',
                        type: 'success',
                        timeout: 1.5,
                    });
                } else {
                    bootoast({
                        message: data.msg,
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            },
            error: function (e) {
                bootoast({
                    message: '保存失败',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    }
    $('#page-wrapper').load('pages/flowchart_table.html');
    setTimeout("$('#data_table').bootstrapTable('refresh');",1500);
}

function saveDiagramProperties() {
    myDiagram.model.modelData.position = go.Point.stringify(myDiagram.position);
}

function loadDiagramProperties(e) {
    // 设置Diagram.initialPosition而不是Diagram.position，以处理初始化副作用
    var pos = myDiagram.model.modelData.position;
    if (pos)
        myDiagram.initialPosition = go.Point.parse(pos);
}

$(document).ready(function () { //进入页面的方法
    if (is_edit) {
        $.ajax({
            type: 'get',
            url: "/chart/selectOne?id=" + flowchartEditId,
            success: function (data) {

                var id = data['result']['id'];
//                var businessId = data['result']['businessId'];
                var chartName = data['result']['chartName'];
                var _data = data['result']['data'];

//                var copy = JSON.parse(_data);
//                for (var i = 0; i < JSON.parse(_data)['nodeDataArray'].length; i++) {
//                    var deviceId = JSON.parse(_data)['nodeDataArray'][i]['select_no']
//                    console.log(deviceId);
//                    if(deviceId != null || typeof a != "undefined") {
//                         var text = copy['nodeDataArray'][i]['text'];
//                         console.log("原始"+text);
//                         var device_data = getDeviceValue(businessId, deviceId);
//                         console.log("替换"+device_data);
//                         copy['nodeDataArray'][i]['text'] = device_data.toString();
//                    }
//                }
//                console.log(copy);
//                myDiagram.model = go.Model.fromJson(JSON.stringify(copy));
                myDiagram.model = go.Model.fromJson(_data);
                loadDiagramProperties(); // 在Model.modelData被带入内存后执行此操作
                document.getElementById("flowchart_name").value = chartName;
            },
            error: function () {
                alert("错误");
            }
        })
    }
})

$("#btn_out").click(function () {
    $('#page-wrapper').load('pages/flowchart_table.html');
    setTimeout("$('#data_table').bootstrapTable('refresh');",1500);
});